const { src, dest, watch, series, parallel } = require('gulp');
const sass = require('gulp-sass')(require('sass'));
const postcss = require('gulp-postcss');
const autoprefixer = require('autoprefixer');
const cssnano = require('cssnano');
const groupMedia = require('gulp-group-css-media-queries');
const plumber = require('gulp-plumber');
const notify = require('gulp-notify');
const del = require('del');
const fileInclude = require('gulp-file-include');
const browserSync = require('browser-sync').create();

// 判断当前是否为生产模式
const isProd = process.env.NODE_ENV === 'production';

// 清理 dist/css
function clean() {
  return del(['dist/css']);
}

// Sass 编译 + 前缀 + 媒体查询 + sourcemap + 压缩
function compileSass() {
  return src('src/sass/**/*.scss')
    .pipe(plumber({ errorHandler: notify.onError("SASS Error: <%= error.message %>") }))
    .pipe(sass().on('error', sass.logError))
    .pipe(groupMedia())
    .pipe(postcss([
      autoprefixer({ overrideBrowserslist: ['last 2 versions'], cascade: false }),
      ...isProd ? [cssnano()] : []
    ]))
    .pipe(dest('dist/css'))
    .pipe(browserSync.stream());
}

// 编译 HTML：拼接 header/footer
function html() {
  return src('src/pages/**/*.html')
    .pipe(fileInclude({
      basepath: 'src/template'  // 从这里开始找 include 文件
    }))
    .pipe(dest('dist'))
    .pipe(browserSync.stream());
}

// 启动本地服务器并监听文件变动
function serve() {
  browserSync.init({
    server: {
      baseDir: './dist'
    },
    port: 3000
  });

  watch('src/sass/**/*.scss', compileSass);
  watch('src/pages/**/*.html', html)
  watch('src/template/**/*.html', html)
}

// 开发任务（含监听）
exports.default = series(clean, compileSass, html, serve);

// 仅构建任务（生产模式打包用）
exports.build = series(clean, compileSass);
